#include "Pixie.h"

/* This stage emits increasing uint16_t value as new memrefs */

generic module CountStageP() {
  provides interface PixieStage;
  uses interface PixieSink;
  uses interface PixieMemAlloc;

} implementation {

  uint16_t count = 0;

  command error_t PixieStage.init() {
    return SUCCESS;
  }

  command error_t PixieStage.run(memref_t dequeuedMR) {

    memref_t newMR = PIXIE_NULL_MEMREF;
    uint8_t *ptrVal;

    count++;

    if (dequeuedMR == PIXIE_NULL_MEMREF) {
      return FAIL;
    } else {
      newMR = call PixieMemAlloc.allocate(sizeof(uint16_t)); 
      ptrVal = call PixieMemAlloc.data(newMR); 
      *ptrVal = count;
    }


    call PixieSink.enqueue(newMR); //pass the new memref downstream
    call PixieMemAlloc.release(newMR); //must release memref after done
    call PixieMemAlloc.release(dequeuedMR); //must release memref after done
    return SUCCESS;
  }
}
